/*
 Copyright 2007 Ole Rogeberg

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
package org.lifeyears.hibernate;

import java.util.Date;

import org.hibernate.event.PreInsertEvent;
import org.hibernate.event.PreInsertEventListener;
import org.hibernate.event.PreUpdateEvent;
import org.hibernate.event.PreUpdateEventListener;
import org.lifeyears.model.AbstractEntity;
import org.lifeyears.services.UserServiceHibernate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A Hibernate Event Listener that updates modificationDate and creation date on entity objects at
 * inserts and updates
 * 
 * @author Aleksander Blomskøld
 */
public class HibernateEventListener
    implements PreUpdateEventListener, PreInsertEventListener
{

    private final Logger log = LoggerFactory.getLogger( UserServiceHibernate.class );

    @Override
    /**
     * Set the modification date to the current time before the object is updated
     */
    public boolean onPreUpdate( final PreUpdateEvent event )
    {
        final Object entity = event.getEntity();

        if ( entity instanceof AbstractEntity )
        {
            final AbstractEntity absEnt = (AbstractEntity) entity;
            log.debug( "Setting modificationDate on preUpdate for object {}", entity );
            absEnt.setModificationDate( new Date() );
        }

        return false;
    }

    @Override
    /**
     * Set the modification date and the creation date to the current time before the object is
     * inserted
     */
    public boolean onPreInsert( final PreInsertEvent event )
    {
        final Object entity = event.getEntity();

        if ( entity instanceof AbstractEntity )
        {
            final AbstractEntity absEnt = (AbstractEntity) entity;

            log.debug( "Setting modificationDate and creationDate on preInsert for object {}", entity );

            final Date date = new Date();
            absEnt.setCreationDate( date );
            absEnt.setModificationDate( date );
        }

        return false;
    }

}
